package com.simple.proxy.mybatis.proxy;

import com.simple.proxy.mybatis.annotations.Select;
import com.simple.proxy.mybatis.annotations.Update;
import com.simple.proxy.mybatis.db.DbTools;
import com.simple.proxy.mybatis.db.TransactionManager;
import com.simple.proxy.mybatis.test.UserInfo;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * mybatis代理
 */
public class MapperProxy implements InvocationHandler {

    /**
     *
     * @param proxy 代理类
     * @param method 目标对象的方法
     * @param args 方法参数
     * @return
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//        System.out.println("JDK动态代理开始");
        //获取方法的返回值类型
        Class<?> returnType = method.getReturnType();
        Object result = null;
        if(method.isAnnotationPresent(Select.class)){
            // 获取sql语句信息
            Select select = method.getAnnotation(Select.class);
            String sql = select.value();
//            System.out.println("sql语句：" + sql);
//            System.out.println("返回值类型：" + returnType);
            //执行数据库的jdbc操作获取信息
            result = selectOne(sql, returnType, args);
        }else if(method.isAnnotationPresent(Update.class)){
            Update update = method.getAnnotation(Update.class);
            String sql = update.value();
//            System.out.println("sql语句：" + sql);
//            System.out.println("返回值类型：" + returnType);

            result = update(sql,args);
        }
//        System.out.println("JDK动态代理结束");
        return result;
    }

    private int update(String sql, Object ...args) throws SQLException {
        Connection connection = TransactionManager.getConnection();
        System.out.println(connection.getClass());
        return DbTools.executeUpdate(connection, sql, args);
    }


    private <T> T selectOne(String sql, Class<T> returnType,Object ...args){
        List<T> list = selectList(sql, returnType, args);
        if(list == null){
            return null;
        }
        return list.get(0);
    }

    private <T> List<T> selectList(String sql, Class<T> returnType,Object ...args){
        return DbTools.executeQuery(sql, returnType, args);
    }
}
